package com.android.clinic.app.http.interceptor;

import com.jiongbull.jlog.JLog;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by cheng on 2018/3/2.
 */
public class ParamsInterceptor implements Interceptor {

    private StringBuilder stringBuilder = new StringBuilder();

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();

        if ("POST".equals(request.method())) {
            if (null != request.body() && request.body() instanceof FormBody) {
                FormBody formBody = (FormBody) request.body();
                Map<String, String> bodyMap = new HashMap<>();
                List<String> nameList = new ArrayList<>();
                int bodySize = formBody.size();
                for (int i = 0; i < bodySize; i++) {
                    nameList.add(formBody.encodedName(i));
                    bodyMap.put(formBody.encodedName(i), URLDecoder.decode(formBody.encodedValue(i).trim(), "UTF-8"));
                }
                Collections.sort(nameList);
                for (int i = 0; i < nameList.size(); i++) {
                    if (bodyMap.get(nameList.get(i)) != null) {
                        stringBuilder.append(nameList.get(i) + "=" + bodyMap.get(nameList.get(i)) + ",");
                    }
                }
                bodyMap.clear();
                nameList.clear();
                stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());
                JLog.d("请求参数: {" + stringBuilder.toString() + "}");
                request = requestBuilder.post(formBody).build();
            }
        }
        return chain.proceed(request);
    }
}
